#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>

using namespace std;

//class Solution {
//public:
//    bool solve(string A, string B) {
//        if (A.size() != B.size()) return false;
//        return (A + A).find(B) != -1;
//    }
//};

struct ListNode 
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};
 
#include <queue>
class Solution {
    struct cmp
    {
        bool operator ()(ListNode* T1, ListNode* T2)
        {
            return T1->val > T2->val;
        }
    };
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, cmp> heap;
        for (auto head : lists)
        {
            if (head != nullptr)
            {
                heap.push(head);
            }
        }
        ListNode* newhead = new ListNode(0);
        ListNode* prev = newhead;
        while (heap.size())
        {
            ListNode* t = heap.top();
            heap.pop();
            prev->next = t;
            prev = prev->next;
            if (t->next != nullptr)
            {
                heap.push(t->next);
            }
        }
        return newhead->next;
    }
};